package comp6231.project.replica.dimitri;
/**
 * Distributed Retail System
 * Oct 4, 2012 
 */


import java.net.*;
import java.io.*;

/**
 * @author dimitri.tiago
 *
 * This class instantiates a udp/ip retail stock client that
 * request the number of items of a specific item in from
 * a udp/id retail stock server.
 */
public class UPDRetailStockClient implements Runnable
{
	private int itemID;
	private int port;
	private int numberOfItems;
	private String operation;

	public UPDRetailStockClient(int itemID, int port)
	{
		this.itemID 	   = itemID;
		this.port 	   	   = port;
		this.numberOfItems = 0;
		this.operation 	   = "check stock";
	}

	public UPDRetailStockClient(int port, int itemID, int numberOfItems)
	{
		this.port          = port;
		this.itemID        = itemID;
		this.numberOfItems = numberOfItems;
		this.operation     = "buy";
	}

	@Override
	public void run()
	{
		DatagramSocket aSocket = null;

		try 
		{
			// instantiate socket for communication
			aSocket = new DatagramSocket();
			InetAddress aHost = InetAddress.getByName("127.0.0.1");
			int serverPort = port;

			// prepare and send request
			String command = String.format("%s %d %d", operation, itemID, numberOfItems);
			byte [] m = command.getBytes(); 
			DatagramPacket request = new DatagramPacket(m, command.length(), aHost, serverPort);
			aSocket.send(request);

			// obtain response 
			byte[] buffer = new byte[1000];
			DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
			aSocket.receive(reply);
			String items = (new String(reply.getData())).trim();
			setNumberOfItems(Integer.parseInt(items));	// store response data
		}
		catch (SocketException e)
		{
			System.out.println("Socket: " + e.getMessage());
		}
		catch (IOException e)
		{
			System.out.println("IO: " + e.getMessage());
		}
		finally 
		{
			if(aSocket != null) aSocket.close();
		} 
	}

	/**
	 * @return the data
	 */
	public int getNumberOfItems()
	{
		return numberOfItems;
	}

	/**
	 * @param data the data to set
	 */
	public void setNumberOfItems(int numberOfItems)
	{
		this.numberOfItems = numberOfItems;
	}
}